import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";

// create an axios instance
const service = axios.create({
  baseURL: "/api", // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
});

// 请求拦截器发起的细节流程
// 1. 先执行请求拦截器
// 2. 请求拦截器执行完成,自动使用返回的config请求配置对象发起请求
// 3. 请求到达后台处理
// 4. 后台返回数据,先走响应拦截器处理
// 5. 响应拦截器返回的内容,才给到调用者接收
// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers.Authorization = "Bearer " + getToken();
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  // http状态码是 200 204 206等等成功的情况
  (response) => {
    console.log("response", response);
    const res = response.data; // res才是接口返回的内容
    if(res instanceof Blob) return res
    // if the custom code is not 20000, it is judged as an error.
    if (res.success) {
      return res.data;
    } else {
      Message.error(res.message);
      return Promise.reject(new Error(res.message || "Error"));
    }
  },
  // http状态码失败的情况
  async (error) => {
    console.log("err" + error); // for debug
    // token失效问题
    if (error?.response?.status === 401) {
      // 2. 清理无效token
      await store.dispatch('user/logout')
      // 3. 去login页面重新获取token
      router.push("/login");
    }
    // 1. 提示错误信息
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });

    return Promise.reject(error);
  }
);

export default service;
